package com.yupi.project.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.project.service.FileService;
import com.yupi.yuapicommon.model.common.ErrorCode;
import com.yupi.yuapicommon.model.common.BusinessException;
import com.yupi.project.mapper.UserMapper;
import com.yupi.project.service.UserService;
import com.yupi.yuapicommon.model.common.ResultUtils;
import com.yupi.yuapicommon.model.dto.user.UserUpdatePwdRequest;
import com.yupi.yuapicommon.model.dto.user.UserUpdateRequest;
import com.yupi.yuapicommon.model.dto.user.UserUpdateSelfRequest;
import com.yupi.yuapicommon.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Objects;

import static com.yupi.yuapicommon.model.constant.UserConstant.*;


/**
 * 用户服务实现类
 *
 * @author yupi
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private FileService fileService;

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String userEmail, String userAvatar) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount).or().eq("userEmail", userEmail);
            long count = userMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复或者邮箱已被注册");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            // 3. 自动分配AK、SK
            String accessKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(5));
            String secretKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(9));
            // 4. 插入数据
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            user.setUserName(userAccount);
            user.setAccessKey(accessKey);
            user.setSecretKey(secretKey);
            user.setUserEmail(userEmail);
            user.setUserAvatar(userAvatar);
            // 上传图片
//            user.setUserAvatar(fileService.fileUpload(advatorImgFile).getData());
            // windows：本地测试
//            user.setUserAvatar(fileService.fileUploadLocal(advatorImgFile).getData());
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    //public static void main(String[] args) {
    //    String encryptPassword = DigestUtils.md5DigestAsHex((SALT + "100200300").getBytes());
    //    System.out.println(encryptPassword);
    //}

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return user;
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && ADMIN_ROLE.equals(user.getUserRole());
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    /**
     * 重新生成AK/SK
     * @param id
     * @return
     */
    @Override
    public boolean genAKSKById(int id) {
        User user = this.getById(id);
        if(user == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        String userAccount = user.getUserAccount();
        String accessKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(5));
        String secretKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(9));
        user.setAccessKey(accessKey);
        user.setSecretKey(secretKey);
        return this.updateById(user);
    }

    @Override
    public void resetPassword(String userEmail, String password) {
        lambdaUpdate()
                .eq(User::getUserEmail, userEmail)
                .set(User::getUserPassword, DigestUtils.md5DigestAsHex((SALT + password).getBytes()))
                .update();
    }

    @Override
    public boolean updateUser(UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        if(!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        Long id = userUpdateRequest.getId();
        String userName = userUpdateRequest.getUserName();
        String userAccount = userUpdateRequest.getUserAccount();
        String userAvatar = userUpdateRequest.getUserAvatar();
        String userEmail = userUpdateRequest.getUserEmail();
        Integer gender = userUpdateRequest.getGender();
        String userRole = userUpdateRequest.getUserRole();
        Long woolLeft = userUpdateRequest.getWoolLeft();
        User loginUser = getLoginUser(request);
        if(StringUtils.isNotBlank(userEmail) && !userEmail.equals(loginUser.getUserEmail()) && Objects.nonNull(getByUserEmail(userEmail))){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该邮箱已被注册");
        }
        return lambdaUpdate()
                .eq(User::getId, id)
                .set(StringUtils.isNotBlank(userName), User::getUserName, userName)
                .set(StringUtils.isNotBlank(userAccount), User::getUserAccount, userAccount)
                .set(StringUtils.isNotBlank(userAvatar), User::getUserAvatar, userAvatar)
                .set(StringUtils.isNotBlank(userEmail), User::getUserEmail, userEmail)
                .set(Objects.nonNull(gender), User::getGender, gender)
                .set(StringUtils.isNotBlank(userRole), User::getUserRole, userRole)
                .set(Objects.nonNull(woolLeft), User::getWoolLeft, woolLeft)
                .update();
    }

    public User getByUserEmail(String userEmail){
        return lambdaQuery().eq(User::getUserEmail, userEmail).one();
    }

    @Override
    public boolean updateUserPwd(UserUpdatePwdRequest userUpdatePwdRequest) {
        Long id = userUpdatePwdRequest.getId();
        User user = this.getById(id);
        String oldPassword = userUpdatePwdRequest.getOldPassword();
        String newPassword = userUpdatePwdRequest.getNewPassword();
        if(StringUtils.isAnyBlank(oldPassword, newPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        String oldMD5Pwd = DigestUtils.md5DigestAsHex((SALT + oldPassword).getBytes());
        if(!user.getUserPassword().equals(oldMD5Pwd)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "原密码不正确");
        }
        return lambdaUpdate()
                .eq(User::getId, id)
                .set(User::getUserPassword, DigestUtils.md5DigestAsHex((SALT + newPassword).getBytes()))
                .update();
    }

    @Override
    public boolean updateSelf(UserUpdateSelfRequest userUpdateSelfRequest, HttpServletRequest request) {
        User loginUser = getLoginUser(request);
        if(Objects.isNull(loginUser)){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Long id = loginUser.getId();
        String userName = userUpdateSelfRequest.getUserName();
        String userAvatar = userUpdateSelfRequest.getUserAvatar();
        String userEmail = userUpdateSelfRequest.getUserEmail();
        Integer gender = userUpdateSelfRequest.getGender();
        return lambdaUpdate()
                .eq(User::getId, id)
                .set(StringUtils.isNotBlank(userName), User::getUserName, userName)
                .set(StringUtils.isNotBlank(userAvatar), User::getUserAvatar, userAvatar)
                .set(StringUtils.isNotBlank(userEmail), User::getUserEmail, userEmail)
                .set(Objects.nonNull(gender), User::getGender, gender)
                .update();
    }

}




